<template>
  <view class="">
    <uv-navbar title="定制" placeholder :autoBack="true"></uv-navbar>

    <view class="page flex-col-ali position-relative">
      <view class="position-absolute" style="right: 0; top: 34rpx;" @click="popupShow.open('center')">
        <uv-image :src="ASSETSURL + 'tishi.png'" width="124rpx" height="56rpx"></uv-image>
      </view>
      <view class="text-main font-36 font-weight-bold m-t-36 m-b-14">请选择您的手串圈长</view>
      <view class="w100 p-x-40">
        <!-- <view class="w100 flex-cen p-l-60 tagImg">
          <uv-image :src="ASSETSURL + 'tag.png'" width="120rpx" height="28rpx"></uv-image>
        </view> -->
        <u-tabs :list="tabsList" lineWidth="52rpx" lineColor="#000" :current="cur" lineHeight="6rpx" @click="click"
          :scrollable="false"
          :itemStyle="{ width: '172rpx', height: '50rpx', 'font-size': '32rpx', 'margin-bottom': '12rpx', color: '#999' }"
          :activeStyle="{ color: ' #1E1E1E', 'font-weight': '700' }"></u-tabs>
        <view class="AIClick" @click="tool.jump_nav('/packageDiy/AIanalytics/AIanalytics')"></view>
      </view>
      <swiper class="swiperContent p-x-40" :current="cur">
        <swiper-item @touchmove.stop="touchmove">
          <view class="swiper-item p-x-40">
            <view class="flex-ali-aro m-t-38">
              <view class="tag" @click="typeCur = 0" :class="{ cur: typeCur == 0 }">女生推荐</view>
              <view class="m-x-8"></view>
              <view class="tag" @click="typeCur = 1" :class="{ cur: typeCur == 1 }">男生推荐</view>
            </view>
            <!-- <view class="font-22 text-666 m-t-28">选择建议：通过卷尺测量您的手腕周长，在该值的基础上增加2CM为适合您的手串圈长。</view> -->
            <view class="m-t-30 position-relative">
				<uv-image :src="ASSETSURL + 'diyIndex_02.png'" width="644rpx" height="258rpx"></uv-image>
				<view @click="popupShow.open('center')" class="position-absolute t-170 r-135" style="width: 198rpx;height: 33rpx;"></view>
			</view>
            <view class="flex-wra-bet m-t-62 p-l-2 listBlock">
              <block v-for="(item, index) in dataList[typeCur]" :key="index">
                <view class="tagItem p-l-20 p-y-24" @click="changeTag(index, item.size)">
                  <view class="font-48 font-weight-bold">
                    {{ item.size }}
                    <text class="font-32">cm</text>
                  </view>
                  <view class="p-r-20">
                    <uv-line color="#D9D9D9" length="100%" margin="16rpx 0"></uv-line>
                  </view>
                  <view class="text-greey">{{ item.description }}</view>
                </view>
              </block>
            </view>
            <!-- <view class="text-center font-26 m-t-100" style="color: #b43742">因珠子直径因素，给您的实际线圈长度选用手围+2cm -->
            <!-- </view> -->
          </view>
        </swiper-item>
        <swiper-item @touchmove.stop="touchmove">
          <view class="swiper-item">
            <uv-form labelPosition="left" labelWidth="auto" class="w100 p-x-40 m-b-50" :labelStyle="labelStyle"
              :model="formData" :rules="rules" ref="form">
              <dy-scale v-model:cur="formData.height" :min="150" :max="190"></dy-scale>
              <view class="m-t-36">
                <dy-scale v-model:cur="formData.weight" :min="minMax[0]" :max="minMax[1]" name="体重"
                  unit="公斤"></dy-scale>
              </view>
              <view class="font-26 p-x-38 flex-ali w100 box m-t-54">
                推荐周长
                <text class="font-32 text-main font-weight-bold m-l-26">{{ perimeter || formData.perimeter }}cm</text>
              </view>
            </uv-form>
            <!-- <view class="text-center font-26" style="color: #b43742">因珠子直径因素，给您的实际线圈长度选用手围+2cm</view> -->
            <dy-button class="m-t-100 fixed-bottom-50 m-x-32" btn_bg="#830102" @click="changeTag(null)">下一步</dy-button>
          </view>
        </swiper-item>
        <swiper-item></swiper-item>
      </swiper>
    </view>
    <uv-popup ref="popupShow" @change="change" :closeOnClickOverlay="false" bgColor="none" round='16rpx'
      :safeAreaInsetBottom='false'>
      <view class="popuShow p-40">
        <view class="font-34 text-center">
          提示
        </view>
        <view class="m-t-26" v-if="configurationData?.prompt_mode == 1">
          {{ configurationData.prompt }}
        </view>
        <view class="m-t-26" v-if="configurationData?.prompt_mode == 2">
          <uv-image :src="configurationData.image" width="506rpx" height="325rpx" mode="widthFix"></uv-image>
        </view>
        <view class="m-t-26" v-if="configurationData?.prompt_mode == 3">
          <video style="width: 100%;" :src="configurationData.video" ref="videoRef" @play="onVideoPlay"></video>
        </view>
      </view>
      <view class="m-t-50 justify-cen flex">
        <uv-image :src="ASSETSURL + 'colse.png'" width="82rpx" height="82rpx" @click="handleClose"></uv-image>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  watch
} from 'vue';
import {
  getConfiguration,
  diyDeductingPoints
} from "@/api/api.js"
import {
  onReady, onShow
} from '@dcloudio/uni-app';
import {
  useCounter
} from '@/mixins/userHooks';
const {
  getUserInfo,
  userInfo,
  isLogin,
  tool
} = useCounter();
import {
  CustomizeCenterApi
} from '../../api/serves';
const popupShow = ref(null)
const configurationData = ref(null)
const videoRef = ref(null)
const form = ref({});
const aiForm = ref(null);
const cur = ref(0);
const error = ref('');
const aiRules = ref({
  // 圈口（需为数字）
  mouth: [{
    required: true,
    message: '请输入圈口',
    trigger: 'blur'
  },
  {
    pattern: /^\d+(\.\d+)?$/,
    message: '请输入有效数字（如 18.5）',
    trigger: 'blur'
  }
  ],

  // 珠子大小（需为数字）
  size: [{
    required: true,
    message: '请输入珠子大小',
    trigger: 'blur'
  },
  {
    pattern: /^\d+(\.\d+)?$/,
    message: '请输入有效数字（如 0.8）',
    trigger: 'blur'
  }
  ],

  // 珠子数量（需为整数）
  num: [{
    required: true,
    message: '请输入珠子数量',
    trigger: 'blur'
  },
  {
    pattern: /^\d+$/,
    message: '请输入整数（如 108）',
    trigger: 'blur'
  }
  ],

  // 风格选择（需选择非空值）
  style: [{
    required: true,
    message: '请选择风格',
    trigger: 'change'
  }],

  // 材质选择（需选择非空值）
  material: [{
    required: true,
    message: '请选择材质',
    trigger: 'change'
  }]
});
const tabsList = ref([{
  name: '快速选择'
},
{
  name: '身高体重'
},
{
  name: 'AI'
}
]);

const dataList = ref([
  [{
    size: '14',
    description: '娇小专属'
  },
  {
    size: '15',
    description: '娇小专属'
  },
  {
    size: '16',
    description: '小骨架女生'
  },
  {
    size: '17',
    description: '大部分女生、精致贴腕'
  },
  {
    size: '18',
    description: '大部分女生、宽松灵动'
  },
  {
    size: '19',
    description: '大骨架女生'
  }
  ],
  [{
    size: '16',
    description: '纤秀专属'
  },
  {
    size: '17',
    description: '纤秀专属'
  },
  {
    size: '18',
    description: '小骨架男生'
  },
  {
    size: '19',
    description: '大部分男生、精致贴腕'
  },
  {
    size: '20',
    description: '大部分男生、宽松灵动'
  },
  {
    size: '21',
    description: '大骨架男生'
  }
  ]
]);
const heightWeightData = ref([]);
const isFallback = ref(false);
const rules = reactive({
  height: {
    type: 'string',
    required: true,
    message: '请选择身高',
    trigger: ['blur', 'change']
  },
  weight: {
    type: 'number',
    required: true,
    message: '请选择体重',
    trigger: ['blur', 'change']
  },
  perimeter: {
    type: 'number',
    required: true,
    message: '请选择身高体重',
    trigger: ['blur', 'change']
  }
});
const formData = ref({
  circles_number: 1,
  height: 170,
  weight: 65,
  perimeter: 15.5
});
const typeCur = ref(0);
const weight = ref([]);
const touchmove = () => { };
const minMax = ref([]);

watch(
  () => [formData.value.height],
  (newVal, oldVal) => {
    let arr = [];
    heightWeightData.value.forEach((item, index) => {
      let heightList = item.value.split('-');
      if (index != heightWeightData.value.length - 1) heightList[1] = heightList[1] - 1;
      if (formData.value.height >= parseInt(heightList[0]) && formData.value.height <= parseInt(
        heightList[1])) {
        arr = [item.weights[0].value, item.weights[item.weights.length - 1].value];
        console.log(minMax.value, arr);
        if (minMax.value[0] != arr[0] || minMax.value[1] != arr[1] || formData.value.weight < arr[
          0] || formData.value.weight > arr[1]) formData.value.weight = arr[0];
        weight.value = item.weights;
      }
    });
    minMax.value = arr;
  }, {
  immediate: true
}
);
const perimeter = ref(0);
watch(
  () => [formData.value.weight],
  (newVal, oldVal) => {
    weight.value.forEach((item) => {
      if (item.value <= formData.value.weight) {
        // formData.value.perimeter = parseFloat(item.wrist_size) + 2;
        formData.value.perimeter = parseFloat(item.wrist_size) + 1
      }
    });
  }, {
  immediate: true
}
);
// 获取题目列表
const getList = async () => {
  let {
    code,
    data,
    msg
  } = await CustomizeCenterApi.getQuestion();
  if (code != 1) return tool.alert(msg);
  heightWeightData.value = data.wrist_reference;
  console.log(heightWeightData.value, '--------');
};
onReady(() => {
  getList();
  getConfigurations();
  // popup.value.open();
});
onShow(() => {
  // cur.value = 0
})
const getConfigurations = () => {
  getConfiguration({
    type: 3
  }).then(res => {
    console.log(res, '--------');
    configurationData.value = res.data
  })
}
const changeTag = (index, size) => {
  formData.value.type = cur.value + 1;
  //扣除积分  接口
  diyDeductingPoints().then(res =>{
	  console.log(res,'-----扣除积分----');
  })
  
  
  if (index == null) {
    form.value
      .validate()
      .then((res) => {
        uni.navigateTo({
          url: '/packageDiy/changeColor/changeColor?formData=' + JSON.stringify(formData
            .value)
        });
      })
      .catch((errors) => {
        uni.$u.toast('校验失败');
      });
    return;
  }
  formData.value.perimeter = size;
  uni.navigateTo({
    url: '/packageDiy/changeColor/changeColor?formData=' + JSON.stringify(formData.value)
  });
};

const labelStyle = reactive({
  color: '#666',
  'font-size': '28rpx'
});

const click = (e) => {
  console.log(e, '---------');
  if (e.name == "AI") {
    return tool.jump_nav('/packageDiy/AIanalytics/AIanalytics')
  } else {
    cur.value = e.index;
    formData.value = {
      circles_number: 1,
      height: 170,
      weight: 65,
      perimeter: 15.5
    };
  }

};

const handleClose = () => {
  if (videoRef.value) {
    videoRef.value.pause()
  }
  popupShow.value.close()
}
</script>
<style>
page {
  background: linear-gradient(180deg, #fff3f4 0%, #fff 27.12%);
}
</style>
<style lang="scss" scoped>
.title {
  color: #1e1e1e;
  font-family: 'Source Han Sans CN';
  font-size: 32rpx;
  font-style: normal;
  font-weight: 500;
  padding: 32rpx 16rpx 8rpx;
  position: relative;

  &::before {
    content: ' ';
    width: 8rpx;
    height: 24rpx;
    background: #830102;
    position: absolute;
    left: -14rpx;
    top: 42rpx;
  }
}

::v-deep .uv-form-item__body {
  padding: 32rpx 0 !important;
}

.tag {
  width: 327rpx;
  height: 78rpx;
  flex-shrink: 0;
  border-radius: 6rpx;
  border: 1px solid #cfcfcf;
  color: #999;
  text-align: center;
  font-size: 28rpx;
  line-height: 78rpx;
}

.cur {
  border: 2rpx solid #1e1e1e;
  color: #000;
}

.swiperContent {
  width: 100%;
  height: calc(100vh - 360rpx);
}

.swiper-item {
  width: 100%;
  height: calc(100vh - 360rpx);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tagItem {
  width: 327rpx;
  flex-shrink: 0;
  border-radius: 12rpx;
  border: 2rpx solid #d9d9d9;
}

.listBlock {
  gap: 25rpx 0rpx;

}



.tag-cur {
  border: #000 solid 1rpx;

  &>view:nth-child(1) {
    color: #830102;

    text {
      color: #830102;
    }
  }
}

.tagImg {
  margin-bottom: -10rpx;
}

.height {
  color: #1e1e1e;
  font-size: 32rpx;
  background-color: transparent;
}

.perimeter {
  color: #830102;
  font-size: 32rpx;
  font-weight: 700;
}

.formInput {
  width: 100%;
  text-align: right;
  margin-right: 15rpx;
}

.result {
  width: 626rpx;
}

.AIClick {
  width: 220rpx;
  height: 70rpx;
  position: absolute;
  top: 85rpx;
  right: 45rpx;
  z-index: 20;
}

.box {
  width: 670rpx;
  height: 82rpx;
  flex-shrink: 0;
  border-radius: 6rpx;
  border: 2rpx solid #d29d9e;
  background: #fff5f6;
}

.popuShow {
  width: 586rpx;
  // height: 314rpx;
  border-radius: 16rpx;
  background: #FFF;
}
</style>